package com.lhy.admin.service;

import com.lhy.admin.mapper.PermissionMapper;
import com.lhy.admin.model.Department;
import com.lhy.admin.model.Permission;
import com.lhy.admin.model.Role;
import com.lhy.admin.model.User;
import com.lhy.admin.model.extend.PermissionGroup;
import com.lhy.admin.util.AuthUtil;
import com.lhy.commonweb.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.common.Mapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class PermissionService extends AbstractService<Permission, Integer> {

    @Autowired
    RoleService roleService;

    @Autowired
    AuthUtil authUtil;

    @Autowired
    DictService dictService;

    public PermissionService(@Qualifier("permissionMapper") Mapper<Permission> mapper) {
        super(mapper);
    }

    public List<Permission> listPermissionsByUserName(String userName) {
        PermissionMapper permissionMapper = getMapper();
        //超级管理员
        User user = authUtil.getUser();
        boolean equals = user.getRoleId().equals(-1);
        if (equals) {
            return permissionMapper.selectAll();
        }
        List<Role> roles = roleService.listRolesByUserName(userName);
        Optional<Role> first = roles.stream()
                .filter(role -> role.getName().equals(authUtil.getCurrentRole().getName()))
                .findFirst();
        if (first.isPresent()) {
            Role role = first.get();
            return permissionMapper.listPermissionsByRoleName(role.getName());
        }
        return new ArrayList<>();
    }

    public List<Permission> listPermissionsByRoleName(String roleName) {
        return PermissionMapper.class.cast(mapper).listPermissionsByRoleName(roleName);
    }

    /**
     * @param permissionGroup
     * @return void
     * @throws
     * @Title: savePermissionWithGroup
     * @Description: 保存权限 包含默认权限组
     * @date 2018/6/11 17:15
     */
    @Transactional(rollbackFor = Exception.class)
    public void savePermissionWithGroup(PermissionGroup permissionGroup) {
        //查询父权限的级别
        Integer level = Optional.ofNullable(permissionGroup.getParent())
                .map(this::get)
                .map(Permission::getLevel)
                .map(integer -> integer + 1).orElse(1);
        //设置当前级别
        permissionGroup.setLevel(level);
        this.add(permissionGroup);
        this.update(permissionGroup.setAncestors(permissionGroup.getAncestors() + permissionGroup.getId()));

        List<Permission> addedGroup = permissionGroup.getAddedGroup();
        if (!CollectionUtils.isEmpty(addedGroup)) {
            //先查询数据库是否已经有和此次添加的权限相同code,parent的 有就不添加
            List<Permission> existPermissions = this.query(new Permission().setCode(permissionGroup.getCode()).setParent(permissionGroup.getId()));
            addedGroup.stream()
                    .map(permission -> permission.setDescription("默认权限组").setParent(permissionGroup.getId()).setLevel(permissionGroup.getLevel() + 1))
                    //有就不添加
                    .filter(permission -> notContains(permission, existPermissions))
                    .forEach(permission -> {
                        this.add(permission);
                        Permission permission1 = new Permission().setId(permission.getId()).setAncestors(permissionGroup.getAncestors() + "," + permission.getId());
                        this.update(permission1);
                    });
        }
    }

    private boolean notContains(Permission permission, List<Permission> existPermissions) {
        return existPermissions.stream()
                .noneMatch(permission1 -> permission1.getCode().equals(permission.getCode()) && permission1.getParent().equals(permission.getParent()));
    }

    /**
     * @param id
     * @return int
     * @throws
     * @Title: delPermission
     * @Description: 根据权限id删除权限和子权限
     * @date 2018/6/11 17:14
     */
    @Transactional(rollbackFor = Exception.class)
    public int delPermission(Integer id) {
        //删除自己
        this.delete(id);
        //删除子权限
        Permission p = new Permission().setParent(id);
        this.deleteCond(p);
        return 2;
    }


}
